import O1HD from "../gameEngine";
import { CsvFileKind } from "../libs/CsvFileKind";
import data_control from "../libs/data_control";
import utilsModel from "../libs/utilsModel";
import SuperManager from "./superManager";

export default class CsvDataManage extends SuperManager{

    async loadManager(): Promise<void> {
        return Promise.resolve();
    }

    gameCsvData: any = {};

    async initCsvList(loadBack?: (progress: number)=>void, loadFinish?: ()=> void) {
        return new Promise<void>(resolve=> {
            let CsvFile = CsvFileKind.CsvFile;
            let csvFile = [
                CsvFile.peopleArcheryTimeLine,
                CsvFile.peopleArcheryTimeLineFile0,
                CsvFile.peopleArcheryTimeLineFile1,
                CsvFile.peopleArcheryTimeLineFile2,
                CsvFile.peopleArcheryTimeLineFile3,
                CsvFile.peopleArcheryOption,
                CsvFile.peopleArcheryOptionDoor,
                CsvFile.peopleArcheryBox,
                CsvFile.cardCompositionLevel,
                CsvFile.bunchbunchbunchLevel,
                CsvFile.goldMinerLevel,
                CsvFile.goldMinerHookLevel,
                CsvFile.goldMinerHoookGooods,
                CsvFile.goldMinerChats,
                CsvFile.peopleArcheryTimeLineFile4,
                CsvFile.peopleArcheryInfinityEnemyHp,
                CsvFile.goldMinerProp,
                CsvFile.peopleArcheryRole,
                CsvFile.peopleArcheryTalent,
                CsvFile.peopleArcheryMagicWeapon,
                CsvFile.peopleArcherySurviveCatastrophe,
            ];
            let csvMapFile: string[] = [
            ];
            let csvFileIndx = 0;
            let csvFileLength = csvFile.length;
            for (let file of csvFile){
                this.loadCsvFile(file, false, ()=> {
                    csvFileIndx++;
                    if (loadBack) {
                        loadBack(csvFileIndx / csvFileLength);
                    }
                    if (csvFileLength <= csvFileIndx) {
                        // 加载完成
                        if (loadFinish) {
                            loadFinish();
                        }
                        resolve();
                    }
                });
            }

            for (let file of csvMapFile){
                this.loadCsvFile(file, true);
            }
        });
    }

    loadCsvFile(filePath: string, bFirstMap: boolean = false, onComplete?: ()=>void) {
        let bundle =  O1HD.getModules().uiControlModule.getGameBundle();
        utilsModel.readCsvData(bundle, filePath, (_data)=>{
            let data = {};
            data['title'] = {}
            
            for (let i in _data[1]){
                data['title'][_data[1][i]] = i;
            }

            let idIndex = data['title'].id ?? 0;
            for(let i = 2; i < _data.length; i++){

                if (bFirstMap) {
                    if (!data[_data[i][idIndex]]) {
                        data[_data[i][idIndex]] = [];
                    }
                    data[_data[i][idIndex]].push(_data[i]);
                } else {
                    data[_data[i][idIndex]] = _data[i];
                }
                
            }
            this.gameCsvData[filePath] = data;

            // Logger.logModel(`CSV File ${name} load Finish`);

            if (onComplete) {
                onComplete();
            }
        });
    }

    getCsvData(name: string){
        if (this.gameCsvData == null) return null;
        if (this.gameCsvData[name] == null) {
            console.warn(`此文件未加载 ${name}`);
            return null;
        }
        return this.gameCsvData[name];
    }

    resetCsvData(name: string) {
        this.gameCsvData[name] = null;
    }

    /**
     * 获取csv中的数据
     * @param csvName 文件名
     * @param id id
     * @param itemName 字段名字，null则是全部字段
     * @returns 
     */
    getCsvDataItem(csvName: string, id: number | string, itemName?: any): any {
        let _infos = this.getCsvData(csvName);
        if (!_infos){
            return null;
        }

        let result = {};
        let _title = _infos.title;
        let info = _infos[id];
        if (!info) {
            return null;
        }

        if (!itemName) {
            for (let n in _title) {
                result[n] = info[_title[n]];
            }
        } else {
            for (let o of itemName) {
                result[o] = info[_title[o]];
            }
        }
        return result;
    }

    getCsvRandomId(csvName: string) {
        let csvInfos = this.getCsvData(csvName);
        if (!csvInfos) {
            console.error(`数据未找到`);
            return null;
        }
        
        let idArr: string[] = this.getCsvIds(csvName);
        let randomIdx = data_control.randomNumInt(0, idArr.length-1);
        let id = idArr[randomIdx];
        return id;
    }

    getCsvRandomIdArr(csvName: string, randomCount: number) {
        let csvInfos = this.getCsvData(csvName);
        if (!csvInfos) {
            console.error(`数据未找到`);
            return null;
        }

        let idArr: string[] = this.getCsvIds(csvName);

        let randomIdx = data_control.randomIntNum(0, idArr.length-1, randomCount);
        let retArr: string[] = [];
        for (let o of randomIdx) {
            retArr.push(idArr[o]);
        }
        return retArr;
    }

    getCsvIds(csvName:string){
        let csvInfos = this.getCsvData(csvName);
    
        if (!csvInfos) {
            console.error(`数据未找到`);
            return [];
        }

        let idArr: string[] = [];
        for (let i in csvInfos) {
            if (i == 'title' || i == '' || i.trim() == '') {
                continue;
            }
            idArr.push(i);
        }
        return idArr;
    }

}
